package com.pku.smart.queue.polling;

import com.alibaba.fastjson.JSON;
import com.pku.smart.config.RabbitmqConfig;
import com.pku.smart.constant.PayConstant;
import com.pku.smart.log.MyLog;
import com.pku.smart.queue.config.PollingConfig;
import com.pku.smart.queue.vopackage.VoPollingRefund;
import com.pku.smart.trade.entity.TradeRefundOrder;
import com.pku.smart.trade.enums.TradePayStatusEnum;
import com.pku.smart.trade.service.IPaymentManagerService;
import com.pku.smart.trade.service.ITradeRefundOrderService;
import com.pku.smart.trade.vopackage.VoReqQueryRefund;
import com.pku.smart.trade.vopackage.VoResQueryRefund;
import com.pku.smart.trade.vopackage.VoResTradePayment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Mq4RefundPolling extends Mq4BasePolling {

    private static final MyLog _log = MyLog.getLog(Mq4RefundPolling.class);

    @Autowired
    PollingConfig pollingConfig;

    @Autowired
    ITradeRefundOrderService refundOrderService;

    @Autowired
    IPaymentManagerService paymentManagerService;

    public void send(final Object msg, final Integer delay) {
        super.send(msg,delay,RabbitmqConfig.POLLING_REFUND_EXCHANGE,RabbitmqConfig.POLLING_REFUND_KEY);
    }

    //监听消息队列
    @RabbitListener(queues = RabbitmqConfig.POLLING_REFUND_QUEUE)
    public void consumeMessage(VoPollingRefund pollingRefund) {
        _log.info("do notify task, msg={}", JSON.toJSONString(pollingRefund));

        //1、解析消息内容
        pollingRefund.setProcessCount(pollingRefund.getProcessCount()-1);
        String mchId = pollingRefund.getMchId();
        String channelId = pollingRefund.getChannelId();
        String mchOrderNo = pollingRefund.getChannelId();
        String mchRefundNo = pollingRefund.getMchRefundNo();
        _log.info("商户号={},渠道编码={},商户退款订单号={}",mchId,channelId,mchRefundNo);
        int count = pollingRefund.getProcessCount();
        _log.info("轮询剩余次数：" + count);
        if (count <= 0){
            _log.error("轮询次数已用尽,跳出!");
            return;
        }

        //2、判断订单是否完成，未完成继续下一步
        TradeRefundOrder refundOrder = refundOrderService.getTradeRefundOrder(mchId,mchRefundNo);
        if (refundOrder == null){
            _log.info("本地退款订单号{}不存在,跳出轮询.",mchRefundNo);
            return;
        }
        if (PayConstant.REFUND_STATUS_SUCCESS.equals(refundOrder.getStatus())){
            _log.info("订单{}已经是退款成功状态",mchRefundNo);
            return;
        }

        //3、查询支付宝微信订单状态
        VoReqQueryRefund requestVo = new VoReqQueryRefund();
        requestVo.setMchId(mchId);
        requestVo.setMchOrderNo(mchOrderNo);
        requestVo.setMchRefundNo(mchRefundNo);
        requestVo.setSign("1");
        try {
            VoResTradePayment tradePayment = paymentManagerService.refundQuery(requestVo);
            if (!PayConstant.TRADE_STATUS_SUCCESS.equals(tradePayment.getRetCode())){
                int cnt = pollingConfig.getCount()-count;
                _log.error("退款订单{}查询未成功，延迟{}秒后继续，继续轮询",mchRefundNo,cnt * 15);
                this.send(pollingRefund, cnt * 15 * 1000);
                return;
            }
            VoResQueryRefund responseVo = (VoResQueryRefund)tradePayment.getRetData();
            String invokeStatus = responseVo.getInvokeStatus();
            if (StringUtils.isNotBlank(invokeStatus) && TradePayStatusEnum.PAY_STATUS_SUCCESS.getCode().toString().equals(invokeStatus)){
                _log.info("退款订单{}支付成功，跳出轮询okk",mchRefundNo);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            int cnt = pollingConfig.getCount()-count;
            _log.error("退款订单{}查询异常，延迟{}秒后继续，继续轮询.本次异常：{}",mchRefundNo,cnt * 15,e.getMessage());
            this.send(pollingRefund, cnt * 15 * 1000);
            return;
        }
        int cnt = pollingConfig.getCount()-count;
        _log.error("退款订单{}未支付成功，延迟{}秒后继续，继续轮询",mchRefundNo,cnt * 15);
        this.send(pollingRefund, cnt * 15 * 1000);
    }

//    /**
//     * 发送延迟消息
//     * @param msg
//     * @param delay
//     */
//    public void send(final String msg, final long delay) {
//        super.send(msg,delay,super.refundPollingQueue);
//    }
//
//    /**
//     * 接收队列消息 处理退款订单状态
//     * @param msg
//     */
//    @JmsListener(destination = ActiveMqConfig.REFUND_POLLING_QUEUE_NAME)
//    public void receive(String msg) {
//        _log.info("do notify task, msg={}", msg);
//
//        //1、解析消息内容
//
//        //2、判断订单是否完成，未完成继续下一步
//
//        //3、查询支付宝微信订单状态
//
//        //4、更新本地订单状态
//    }
}
